<?php

namespace App\Http\Controllers;

use App\Model\Sncode;
use App\Model\User;
use App\Uitls\EncryptionKohana;
use App\Utils\RetUtil;
use App\Utils\WechatUtils;
use GuzzleHttp\Client;
use Illuminate\Http\Request;


class LoginController extends Controller
{
    /**
     * 类的介绍 ：获取微信用户CODE码
     *
     * @Time 2020/8/20 14:38
     * @User  Mr.w
     * @param Request $request
     */
    public function getWxCode(Request $request)
    {
        $client = new Client();
        info('code码 接口被请求了 => ' . $request->get('code'));
        if ($request->get('code') == null) {
            return RetUtil::error('请输入正确的参数！');
        }
        $res = $client->get('https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . config('app.wx.wx_app_id') . '&secret=' . config('app.wx.wx_secret') . '&code=' . $request->code . '&grant_type=authorization_code');
        $data = json_decode($res->getBody());
        if (isset($data->errcode)) {
            info("code码失效" . $data->errcode);
            return RetUtil::ret(401, 'code码失效！');
        }
        $wx = new WechatUtils();
        $open_id = $data->openid;
        $date = $wx->getUserInfo($open_id);
        if ($date->subscribe ==1) {
            $user=new User();
            $user->name=$date->nickname;
            $user->sex=$date->sex;
            $user->open_id=$date->openid;
            $user->save();
            return RetUtil::success(['openid'=>$open_id,'name'=>$date->nicname,'headimgurl'=>$date->headimgurl]);

        }
        return RetUtil::success(['openid'=>$open_id,'name'=>null,'headimgurl'=>null]);
    }

public function getSN(Request $request){
        $sn_code=$request->get('sn');
        if ($sn_code==null){
            RetUtil::error('参数传输失败！');
        }
        $jm_sn=substr($sn_code,5,10);
        $sn=Sncode::where('sn',$jm_sn)->where('status',0)->first();
        if ($sn==null){
            return RetUtil::error('sn输入错误或者该红包已被领取！');
        }
        //微星红包到账
        $fige=true;
        if ($fige){
            return RetUtil::success('红包领取成功！');
        }
            return RetUtil::error('红包领取失败，请重试！');





}


}
